from flask import abort, jsonify
from flask import current_app
from flask import g
from flask import render_template
from flask import request

from info import constants, db
from info.models import News, Comment, CommentLike
from info.utils.common import user_login_data
from info.utils.response_code import RET

from . import news_blu


@news_blu.route('/comment_like', methods=['POST'])
@user_login_data
def comment_like():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='请先登陆')
    #  获取数据
    comment_id = request.json.get('comment_id')
    action = request.json.get('action')
    news_id = request.json.get('news_id')

    if not all([comment_id, action, news_id]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不足')

    try:
        comment_id = int(comment_id)
        news_id = int(news_id)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')

    if action not in ['add','remove']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')

    #  查询评论,并判断评论是否存在
    try:
        comment = Comment.query.get(comment_id)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.DATAERR, errmsg='数据库错误')
    if not comment:
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')

    #  查询新闻
    if action == 'add':
        c = CommentLike()
        c.comment_id = comment_id
        c.user_id = user.id
        db.session.add(c)
        comment.like_count += 1
    else:
        c = CommentLike.query.filter_by(comment_id=comment_id, user_id=user.id).first()
        if c:
            db.session.delete(c)
            comment.like_count -= 1

    try:
        db.session.commit()
    except Exception as ret:
        db.session.rollback()
        current_app.logger.error(ret)
        return jsonify(errno=RET.DATAERR, errmsg='数据库操作错误')

    return jsonify(errno=RET.OK, errmsg='操作成功')


@news_blu.route('/news_comment', methods=['post'])
@user_login_data
def news_comment():
    #  获取数据
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='请先登陆')

    args_dict = request.json
    news_id = args_dict.get('news_id')
    comment = args_dict.get('comment')
    parent_id = args_dict.get('parent_id')

    if not all([news_id, comment]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不足')

    try:
        news_id = int(news_id)
        if parent_id:
            parent_id = int(parent_id)
    except Exception as ret:
            current_app.logger.error(ret)
            return jsonify(errno=RET.PARAMERR, errmsg='参数有误')

    c = Comment()
    c.user_id = user.id
    c.news_id = news_id
    c.content = comment
    if parent_id:
        c.parent_id = parent_id
    try:
        news = News.query.get(news_id)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.DATAERR, errmsg='查询错误')

    try:
        db.session.add(c)
        db.session.commit()
    except Exception as ret:
        db.session.rollback()
        current_app.logger.error(ret)
        return jsonify(errno=RET.DATAERR, errmsg='提交评论失败')

    count = len(news.comments.all())

    return jsonify(errno=RET.OK, errmsg='操作成功',data=c.to_dict(), count=count)


@news_blu.route('/news_collect', methods=['post'])
@user_login_data
def collect():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='请先登陆')
    args_dict = request.json

    action = args_dict.get('action')
    news_id = args_dict.get('news_id')

    if not news_id:
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')

    try:
        news_id = int(news_id)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')
    #  查询新闻,判断新闻是否存在
    try:
        news = News.query.get(news_id)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.DATAERR, errmsg='查询错误')

    if action not in ['collect', 'cancel_collect']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')

    if not news:
        return jsonify(errno=RET.DATAEXIST, errmsg='查询的新闻不存在')

    #  收藏
    if action == 'collect':
        if news not in user.collection_news:
            user.collection_news.append(news)
    #  取消收藏
    else:
        if news in user.collection_news:
            user.collection_news.remove(news)
    return jsonify(errno=RET.OK,errmsg='操作成功')


@news_blu.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):
    #  查询用户登陆信息
    user = g.user
    # 显示点击排行的逻辑
    news_dict = []
    try:
        news_dict = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as ret:
        news_dict = [news.to_basic_dict() for news in news_dict]

    # 查询新闻数据
    news = None

    try:
        news = News.query.get(news_id)
    except Exception as ret:
        current_app.logger.error(ret)

    if not news:
        #  如果没有查询到新闻,报404错误后续统一处理
        abort(404)
    #  访问详情页,点击量加1
    news.clicks += 1
    #  默认没有登陆没有收藏
    is_collected = False
    if user:
        if news in user.collection_news:
            is_collected = True
    #  查询当条新闻所有评论
    comments = []
    try:
        comments = Comment.query.filter(Comment.news_id == news.id).order_by(Comment.create_time.desc()).all()
    except Exception as ret:
        current_app.logger.error(ret)
    c = []
    if user:
        try:
            #  查询当条新闻所有评论的ID
            comments_id = [comment.id for comment in comments]
            #  查询当条新闻当个用户所有的被点赞的评论
            comments_like = CommentLike.query.filter(CommentLike.comment_id.in_(comments_id),
                                                     CommentLike.user_id == user.id).all()
            #  取出每条被点赞的评论的评论ID
            c = [i.comment_id for i in comments_like]
        except Exception as ret:
            current_app.logger.error(ret)
    comments_list = []
    for i in comments:
        j = i.to_dict()
        j['is_like'] = False
        if i.id in c:
            j['is_like'] = True
        comments_list.append(j)

    #  查询点赞

    data = {
        'user': user.to_dict() if user else None,
        'news_dict': news_dict,
        'news': news.to_dict(),
        'is_collected': is_collected,
        'comments': comments_list
    }

    return render_template('news/detail.html',data=data)